
package org.scalabletype.ws;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;

import com.xerox.amazonws.common.JAXBuddy;

import org.scalabletype.ws.jaxb.Atlas;
import org.scalabletype.ws.jaxb.ObjectFactory;


/**
 * This class serves the requested page, passing context parameters
 *
 * @author D. Kavanagh
 */
public class RootServlet extends javax.servlet.http.HttpServlet {
	private File indexFile;
	private ServletContext context;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
		this.context = config.getServletContext();
		indexFile = new File(this.context.getRealPath("index.html"));
    }

    /**
     * This method returns 
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

		try {
			response.setContentType("text/html");
			InputStream iStr = new FileInputStream(indexFile);
			String path = request.getPathInfo();
			System.out.println("requested resource : "+path);
			int idx = path.indexOf("/resources");
			if (idx > -1) {
				iStr = new FileInputStream(this.context.getRealPath(path.substring(idx)));
			}
			OutputStream oStr = response.getOutputStream();
			Copier.copyStreams(iStr, oStr);
			response.flushBuffer();
		} catch (Throwable t) {
			// pretty serious error
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unexpected error : "+t.getMessage());
			t.printStackTrace();
		} finally {
        	response.flushBuffer();
		}
    }
}
